from django.db import models
from django.db.models import Q
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver

from order.models import Order
from users.models import Position
from django.utils import timezone
from stock.models import Stock


# Create your models here.
class Transaction(models.Model):
    buy_order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='buy_transaction', verbose_name='买订单id')
    sell_order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='sell_transaction',
                                   verbose_name='卖订单ID')
    dealed = models.IntegerField(verbose_name='成交数量')
    price = models.DecimalField(verbose_name='成交价格', decimal_places=3, max_digits=10)
    ctime = models.DateTimeField(verbose_name='创建时间', default=timezone.now, null=True)
    stock = models.IntegerField(verbose_name='股票id')

    def __str__(self):
        return self.buy_order.name + self.sell_order.name

    class Meta:
        ordering = ['-ctime']


from django_redis import get_redis_connection

redis_con = get_redis_connection()


def updateStockInfo(instance):
    stock_obj = Stock.objects.filter(id=instance.buy_order.stock_id)[0]
    last_price = stock_obj.latest_price
    cur_price = instance.price
    stock_obj.latest_price = cur_price
    stock_obj.latest_num = instance.dealed
    stock_obj.change_rate = (float(cur_price)-float(last_price))/float(last_price)/100
  #  stock_obj.total_price = stock_obj.total_num * cur_price
    print(stock_obj)
    stock_obj.save()


@receiver(post_save, sender=Transaction)
def autoexchange(sender, instance, **kwargs):
    buyer = instance.buy_order.user
    seller = instance.sell_order.user
    precny2 = seller.cny_free
    total_cny = instance.dealed * float(instance.price)
    seller.cny_free = total_cny + float(seller.cny_free)
    updateStockInfo(instance)
    print(type(instance.dealed), type(instance.price), type(seller.cny_free))
    buy_list = Position.objects.filter(user=buyer, stock_id=instance.buy_order.stock_id)
    if buy_list.count() == 0:
        Position.objects.create(user=buyer, stock_id=instance.buy_order.stock_id, num_free=instance.dealed)
        print("该用户不持有股票 创建")
    else:
        pos_instance = buy_list.first()
        pos_instance.num_free += instance.dealed
        pos_instance.save()
        print("该用户持有 更新持有数")
    buyer.save()
    seller.save()
    #    redis_con.lpush('transactions',instance)
    print("匹配到了一个订单 买家为{0} 卖家为{1} 成交金额为{2}卖家的余额从{3}变为{4}".format(buyer.username, seller.username,
                                                                 instance.price * instance.dealed, precny2,
                                                                 seller.cny_free))
